import store from './store'
import router from './router'
// import { dynamicRouter } from './router'

const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (store.getters.userId) {
        next()
      } else {
        // await解决异步问题
        await store.dispatch('user/getInfo')
        // const menus = store.state.user.userInfo.roles.menus
        // const myAuth = dynamicRouter.filter(item => {
        //   return menus.includes(item.children[0].name)
        // })
        const myAuth = await store.dispatch('permission/filterDynamicRoutes')
        // 配置404页面 用[]包括起来
        // 注意：404的路由映射必须放到最底部（路由匹配自上而下）
        router.addRoutes([...myAuth, {
          path: '*',
          redirect: '/404',
          hidden: true }])
        next({
          ...to,
          replace: true
        })
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

